<template>
  <div v-loading.lock="loading" class="base-content">
    <div class="basic-info">
      <el-table
        ref="queryForm"
        :data="list"
        element-loading-text="Loading"
        class="filter unsetborder"
        :class="{ 'show-filter': showFilterRow }"
        height="calc(92%)"
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55">
          <el-table-column type="selection"></el-table-column>
        </el-table-column>
        <el-table-column align="center" width="50">
          <template #header>
            <div class="filter-icon" title="筛选">
              <SvgIcon
                class-name="filter"
                icon-class="filter"
                @click="filterIconClick"
              />
            </div>
          </template>
          <el-table-column width="50"></el-table-column>
        </el-table-column>
        <el-table-column label="任务编号">
          <el-table-column prop="entrustTaskNum">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="queryForm.entrustTaskNum"
                @keyup.enter.native="getList"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="委托单编号">
          <el-table-column prop="entrustOrderNumList">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="queryForm.entrustOrderNum"
                @keyup.enter.native="getList"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="委托单位">
          <el-table-column prop="entrustCommpany">
            <!-- <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="queryForm.entrustCommpany"
                @keyup.enter.native="getList"
              ></el-input>
            </template> -->
          </el-table-column>
        </el-table-column>
        <el-table-column label="样品编号">
          <el-table-column prop="sampleInfoNum">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="queryForm.sampleNum"
                @keyup.enter.native="getList"
              ></el-input>
            </template>
            <template slot-scope="scope">
              <el-link type="primary" @click="toSample(scope.row)">{{
                scope.row.sampleInfoNum
              }}</el-link>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="检测项目">
          <el-table-column prop="detectionItemName">
            <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="queryForm.detectionItemName"
                @keyup.enter.native="getList"
              ></el-input>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="受检单位">
          <el-table-column prop="detectionCommpany">
            <!-- <template #header>
              <el-input
                v-if="showFilterRow"
                v-model="queryForm.detectionCommpany"
                @keyup.enter.native="getList"
              ></el-input>
            </template> -->
          </el-table-column>
        </el-table-column>
        <el-table-column label="状态">
          <el-table-column prop="entrustTaskStatusChar">
            <template #header>
              <el-select
                v-if="showFilterRow"
                v-model="queryForm.entrustTaskStatus"
              >
                <el-option
                  v-for="item in entrustTaskStatusList"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="接收时间">
          <el-table-column>
            <template #header>
              <el-date-picker
                v-model="queryForm.receiveDateList"
                type="datetimerange"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                align="right"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </template>
            <template slot-scope="scope">
              {{ formatTime(scope.row.receiveDate) }}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="操作">
          <el-table-column width="140">
            <template #header>
              <div v-if="showFilterRow" class="search-operate">
                <el-link type="primary" @click="getList(true)">搜索</el-link>
                <el-link @click="cancelForm">清空</el-link>
              </div>
            </template>
            <template slot-scope="scope">
              <div class="base-table-operation">
                <el-link
                  v-if="scope.row.entrustTaskStatus === 9"
                  type="primary"
                  @click="entrustTaskReceiveUpdateFun(scope.row)"
                  >确认接收</el-link
                >
                <el-link
                  v-if="scope.row.entrustTaskStatus === 9"
                  type="primary"
                  @click="entrustTaskDistributionFun(scope.row)"
                  >转单</el-link
                >
                <el-link
                  v-if="scope.row.entrustTaskStatus === 10"
                  type="primary"
                  @click="addSampleCollection(scope.row)"
                  >样品领取</el-link
                >
                <el-link
                  v-if="
                    scope.row.entrustTaskStatus === 11 ||
                    scope.row.entrustTaskStatus === 21
                  "
                  type="primary"
                  @click="dialogShow(scope.row)"
                  >数据录入</el-link
                >
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <BasePagination
        :total="pagination.total"
        :page-index="pagination.pageIndex"
        :page-size="pagination.pageSize"
        @sizeChange="sizeChange"
        @changePage="currentChange"
      />
    </div>
    <el-dialog
      v-if="dialogFormVisible"
      v-loading.lock="loading"
      class="base-dialog"
      :custom-class="'panna-dialog_medium'"
      title="转单"
      align="center"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      @closed="cancelForm2"
    >
      <el-form
        ref="formData"
        :model="formData"
        status-icon
        :rules="rules"
        class="receivePerson"
      >
        <el-form-item
          label="接收人"
          :label-width="formLabelWidth"
          prop="receivePersonId"
        >
          <el-select
            v-model="formData.receivePersonId"
            filterable
            placeholder="接收人"
          >
            <el-option
              v-for="item in userArrary"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="entrustTaskReassignmentUpdateFun()"
          >确 定</el-button
        >
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <SampleCollectionEdit
      v-if="dialogFormSampleVisible"
      ref="SampleCollectionEdit"
      :dialog-form-visible.sync="dialogFormSampleVisible"
      :row-data.sync="rowData"
      @closeSampleCollectionDialog="closeSampleCollectionDialog"
    />
    <EntrustTaskDataResult
      v-if="dialogFormResultVisible"
      ref="EntrustTaskDataResult"
      :dialog-form-visible.sync="dialogFormResultVisible"
      :sample-info-id="sampleInfoId"
      :detection-item-id="detectionItemId"
      :data="choiceData"
      :update-state.sync="updateState"
      @close="close"
    />
  </div>
</template>

<script>
import { getUserListNoPage } from "../../../api/Permission/PermissionUser";
import SampleCollectionEdit from "@/ModuleSample/views/SampleManage/SampleCollection/SampleCollectionEdit.vue";
import EntrustTaskDataResult from "../../../components/EntrustTaskManage/EntrustTaskDataResult.vue";
import { SampleWhetherCollection } from "../../../api/EntrustTaskManage/SampleCollection";
import {
  entrustTaskNoticedList,
  entrustTaskReceiveUpdate,
  entrustTaskReassignmentUpdate,
} from "../../../api/EntrustTaskManage/EntrustTask.js";
import { getConfigByKey } from "../../../api/System/SystemDict";
import { formatTime } from "../../../utils/time";

export default {
  name: "MyTaskList",
  components: {
    SampleCollectionEdit,
    EntrustTaskDataResult,
  },
  data() {
    return {
      formatTime,
      showFilterRow: false,
      entrustTaskStatusList: [
        { key: -1, value: "全部" },
        { key: 9, value: "未接收" },
        { key: 10, value: "待样品领取" },
        { key: 11, value: "待数据录入" },
        { key: 12, value: "数据审核中" },
        { key: 20, value: "已完成" },
        { key: 21, value: "已撤回" },
      ],
      rowData: [],
      sampleInfoId: 0,
      updateState: false,
      detectionItemId: 0,
      choiceData: {},
      userArrary: [],
      receiveTaskId: 0,
      formData: {
        receivePersonId: "",
      },
      tableDatas: [],
      loading: true,
      list: [],
      queryForm: {
        entrustTaskNum: "",
        entrustOrderNum: "",
        entrustCommpany: "",
        sampleNum: "",
        detectionItemName: "",
        detectionCommpany: "",
        entrustTaskStatus: -1,
        receiveDateList: [],
      },
      dialogFormSampleVisible: false,
      dialogFormResultVisible: false,
      dialogFormVisible: false,
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      systemType: "",
    };
  },
  created() {
    // 查询字典表判断系统类型
    getConfigByKey("SystemType").then((res) => {
      this.systemType = res.data[0].value;
    });
    this.getUserListNoPageFun();
    this.getList("filter");
  },
  methods: {
    dialogShow(row) {
      this.choiceData = row;
      this.dialogFormResultVisible = true;
    },
    filterIconClick() {
      this.showFilterRow = !this.showFilterRow;
      !this.showFilterRow && this.cancelForm();
    },
    // 关闭弹框
    close() {
      this.getList();
    },
    closeSampleCollectionDialog() {
      this.rowData = [];
      this.getList();
    },
    // 样品领取
    addSampleCollection(row) {
      this.rowData = [];
      var taskSampleInfoIdList = row.taskSampleInfoIdList;
      // 委托单和样品Id
      for (var i = 0; i < row.sampleInfoList.length; i++) {
        var obj = {};
        obj.entrustTaskIdList = row.entrustTaskIdArray;
        obj.sampleId = row.sampleInfoList[i].id;
        obj.sampleNum = row.sampleInfoList[i].sampleNum;
        obj.entrustTaskNum = row.entrustTaskNum;
        obj.sampleName = row.sampleInfoList[i].sampleName;
        obj.detectionItemName = row.detectionItemName;
        obj.sampleCount = row.sampleInfoList[i].sampleCount;
        obj.storageLocation = row.sampleInfoList[i].storageLocation;
        obj.sampleRegistrationId = row.sampleInfoList[i].sampleRegistrationId;
        obj.entrustTaskId = row.sampleInfoList[i].entrustTaskId;
        obj.sampleCollectionDate = formatTime(new Date());
        obj.sampleCollectionCount = 1;
        obj.taskSampleInfoIdList = row.taskSampleInfoIdList;
        this.rowData.push(obj);
      }

      if (this.moduleEnableDetection) {
        SampleWhetherCollection(taskSampleInfoIdList).then((res) => {
          if (res.data) {
            this.$message({
              message: "样品已领取,请重新选择数据",
              type: "warning",
            });
            return false;
          } else {
            this.dialogFormSampleVisible = true;
          }
        });
      } else {
        this.dialogFormSampleVisible = true;
      }
    },
    getUserListNoPageFun() {
      var pars = {};
      this.userArrary = [];
      getUserListNoPage(pars)
        .then((res) => {
          this.userArrary = res.data.filter(
            (item) => item.id !== this.$store.getters.currentUserId
          );
        })
        .catch((res) => {});
    },
    // 接收任务
    entrustTaskReceiveUpdateFun(row) {
      debugger;
      var obj = {};
      obj.IdList = [];
      obj.IdList.push(row.id);
      entrustTaskReceiveUpdate(obj)
        .then((res) => {
          if (res.code === 200) {
            this.submitLoad = true;
            this.getList("filter");
          }
        })
        .catch((res) => {
          this.$message.warning("操作失败");
          this.submitLoad = true;
        });
    },
    entrustTaskDistributionFun(row) {
      this.receiveTaskId = row.id;
      this.dialogFormVisible = true;
    },
    // 转派任务
    entrustTaskReassignmentUpdateFun() {
      this.$refs["formData"].validate((valid) => {
        if (valid) {
          var obj = {};
          obj.IdList = [];
          obj.IdList.push(this.receiveTaskId);
          obj.ReceivePersonId = this.formData.receivePersonId;
          entrustTaskReassignmentUpdate(obj)
            .then((res) => {
              if (res.code === 200) {
                this.$message.success("转单成功");
                this.receiveTaskId = 0;
                this.dialogFormVisible = false;
                this.submitLoad = true;
                this.getList();
              }
            })
            .catch((res) => {
              this.$message.warning("操作失败");
              this.receiveTaskId = 0;
              this.submitLoad = true;
            });
        }
      });
    },
    toSample(row) {
      this.$router.push("/SampleManageList?sampleNumList=" + row.sampleInfoNum);
    },
    currentChange(val) {
      this.pagination.pageIndex = val;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList("filter");
    },
    getList(flag) {
      if (flag) {
        this.pagination.pageIndex = 1;
      }
      if (this.queryForm.receiveDateList.length > 0) {
        this.queryForm.startReceiveDate = this.queryForm.receiveDateList[0];
        this.queryForm.endReceiveDate = this.queryForm.receiveDateList[1];
      }
      const pars = this.queryForm;
      pars.detectionPersonId = this.$store.getters.currentUserId;
      this.loading = true;
      this.entrustTaskNoticedListFun({
        ...pars,
        ...this.pagination,
      });
    },
    entrustTaskNoticedListFun(obj) {
      this.list = [];
      entrustTaskNoticedList(obj)
        .then((res) => {
          if (res.code === 200) {
            if (res.data.dataList.length <= 0) {
              return;
            }
            this.pagination.total = res.data.total;
            for (var j = 0; j < res.data.dataList.length; j++) {
              var obj = {};
              obj.id = res.data.dataList[j].id;
              obj.entrustTaskIdList = res.data.dataList[j].entrustTaskIdArray;
              obj.sampleInfoList = res.data.dataList[j].sampleInfoList;
              obj.taskSampleInfoIdList =
                res.data.dataList[j].taskSampleInfoIdList;
              obj.id = res.data.dataList[j].id;
              obj.entrustTaskStatus = res.data.dataList[j].entrustTaskStatus;
              obj.entrustCommpany = res.data.dataList[j].entrustCommpany;
              obj.detectionCommpany = res.data.dataList[j].detectionCommpany;
              // 实验记录单数量
              obj.experimentRecordOrderCount =
                res.data.dataList[j].experimentRecordOrderCount;
              obj.entrustTaskNum = res.data.dataList[j].entrustTaskNum; // 任务编号
              obj.detectionItemName = res.data.dataList[j].detectionItemName; // 检测项目
              obj.entrustOrderNumList =
                res.data.dataList[j].entrustOrderNumList; // 委托单号
              obj.sampleInfoName = res.data.dataList[j].sampleInfoName; // 样品名称
              obj.sampleInfoNum = res.data.dataList[j].sampleInfoNum; // 样品编号
              obj.experimentRecordOrder = ""; // 实验记录单
              obj.experimentRecordDate =
                res.data.dataList[j].experimentRecordDate; // 检测日期
              obj.detectionPersonName =
                res.data.dataList[j].detectionPersonName; // 分配检测人
              obj.planDetectionDate = res.data.dataList[j].planDetectionDate; // 分配时间
              obj.receivePersonName = res.data.dataList[j].receivePersonName; // 实际接收人
              obj.receiveDate = res.data.dataList[j].receiveDate; // 接收时间
              obj.entrustTaskStatusChar =
                res.data.dataList[j].entrustTaskStatusChar; // 任务状态
              obj.remark = res.data.dataList[j].remark; // 备注
              this.list.push(obj);
            }

            this.loading = false;
          }
        })
        .catch((res) => {
          this.loading = false;
        });
    },

    onQuery() {
      this.getList();
    },
    handleSelectionChange(val) {
      this.tableDatas = val;
    },
    // 清空筛选条件
    cancelForm() {
      this.queryForm = this.$options.data().queryForm;
      this.getList();
    },
    // 清空筛选条件
    cancelForm2() {
      this.formData = this.$options.data().formData;
    },
  },
};
</script>
